package blue.blog.pic;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blue.crawler.annotation.CrawlerConfig;
import com.blue.crawler.engine.ListDetailCrawl;

import blue.blog.core.model.CmsDoc;
import blue.blog.core.service.CmsDocService;
import blue.blog.util.CmsDocConvertor;

@Component
public class Mistar8Crawl implements ListDetailCrawl<Mistar8Model>
{
	private static Logger logger = LoggerFactory.getLogger(Mistar8Crawl.class);
	
	private static final String URL = "/d/%s-%s";
	
	@Resource
	private CmsDocService cmsDocService;
	
	public Mistar8Crawl()
	{
	}

	@Override
	public List<Mistar8Model> queryList(String html, CrawlerConfig config)
	{
		List<Mistar8Model> list = new ArrayList<>();
		JSONObject root = JSON.parseObject(html);
		JSONArray datas = root.getJSONArray("data");
		for (Object d : datas)
		{
			JSONObject data = (JSONObject)d;
			String id = data.getString("id");
			JSONObject attr = data.getJSONObject("attributes");
			String title = attr.getString("title");
			String slug = attr.getString("slug");
			String startTime = attr.getString("startTime").replace("+00:00", "");
			
			Mistar8Model model = new Mistar8Model();
			list.add(model);
			model.setUrl(String.format(URL, id, slug));
			model.setTitle(title);
			model.setCreateTime(LocalDateTime.parse(startTime));
		}
		
		return list;
	}

	@Override
	public List<String> query(String html, CrawlerConfig config, Mistar8Model model)
	{
		List<String> picList = new ArrayList<>();
		StringBuilder content = new StringBuilder(64);
		Document doc = Jsoup.parse(html);
		Element pNode = doc.select("noscript div.Post-body").first();
		for (Element imgNode : pNode.select("img"))
		{
			String pic = imgNode.attr("src").trim();
			picList.add(pic);
			
			content.append(String.format("<p><img src=\"%s\" /></p>\n", pic));
		}
		
		model.setContent(content.toString());
		return picList;
	}

	@Override
	public List<String> queryPage(String html, CrawlerConfig config, Mistar8Model model, int page)
	{
		return null;
	}

	@Override
	public boolean existUrl(String url)
	{
		return cmsDocService.exist(url);
	}

	@Override
	public void handleModel(CrawlerConfig config, Mistar8Model model)
	{
		CmsDoc doc = CmsDocConvertor.toDoc(model, 3);
		logger.info("保存：{}", model.getTitle());
		cmsDocService.add(doc);
	}
	
}
